package com.team.order.controller;

import com.team.common.core.web.controller.BaseController;
import com.team.common.core.web.domain.AjaxResult;
import com.team.common.log.annotation.Log;
import com.team.common.log.enums.BusinessType;
import com.team.order.domain.RepairReservation;
import com.team.order.domain.RepairReservationVO;
import com.team.order.service.RepairService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 维修预约控制器
 * @author 梁国瑞
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/repair")
@RequiredArgsConstructor
@Validated
public class RepairController extends BaseController {

    private final RepairService repairService;

    /**
     * 创建维修预约
     */
    @Log(title = "创建维修预约", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult addRepair(@Valid @RequestBody RepairReservation repairReservation) {
        try {
            // 设置提交时间
            repairReservation.setSubmitTime(new Date());
            // 设置初始状态
            repairReservation.setStatus("0"); // 0-已预约
            repairReservation.setDelFlag("0"); // 0-存在
            
            Long id = repairService.addRepair(repairReservation);
            if (id != null) {
                log.info("创建维修预约成功，用户ID：{}，预约时间：{}", repairReservation.getUserId(), repairReservation.getReservationTime());
                return AjaxResult.success("预约成功", id);
            } else {
                return AjaxResult.error("预约失败");
            }
        } catch (Exception e) {
            log.error("创建维修预约失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 修改维修预约
     */
    @Log(title = "修改维修预约", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public AjaxResult updateRepair(@Valid @RequestBody RepairReservation repairReservation) {
        try {
            int result = repairService.updateRepair(repairReservation);
            if (result > 0) {
                log.info("修改维修预约成功，预约ID：{}", repairReservation.getId());
                return AjaxResult.success("修改成功");
            } else {
                return AjaxResult.error("修改失败");
            }
        } catch (Exception e) {
            log.error("修改维修预约失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 查询维修预约列表
     */
    @GetMapping("/list")
    public AjaxResult getReservationList(
        @RequestParam(required = false) Long merchantId,
        @RequestParam(required = false) String status) {
        try {
            List<RepairReservation> list = repairService.getReservationList(merchantId, status);
            // 转换为VO，id转为字符串，其他字段不变
            List<RepairReservationVO> voList = list.stream().map(item -> {
                RepairReservationVO vo = new RepairReservationVO();
                vo.setId(item.getId() == null ? null : String.valueOf(item.getId()));
                vo.setVerificationCode(item.getVerificationCode());
                vo.setVerificationImg(item.getVerificationImg());
                vo.setMerchantId(item.getMerchantId());
                vo.setUserId(item.getUserId());
                vo.setType(item.getType());
                vo.setCustomerName(item.getCustomerName());
                vo.setPhoneNumber(item.getPhoneNumber());
                vo.setReservationTime(item.getReservationTime());
                vo.setSubmitTime(item.getSubmitTime());
                vo.setPickupLocation(item.getPickupLocation());
                vo.setCarTypeId(item.getCarTypeId());
                vo.setLicensePlate(item.getLicensePlate());
                vo.setVehiclePhotos(item.getVehiclePhotos());
                vo.setRepairPhotos(item.getRepairPhotos());
                vo.setStatus(item.getStatus());
                vo.setDelFlag(item.getDelFlag());
                return vo;
            }).collect(Collectors.toList());
            log.info("查询维修预约列表成功，商户ID：{}，状态：{}，数量：{}", merchantId, status, voList.size());
            return AjaxResult.success("查询成功", voList);
        } catch (Exception e) {
            log.error("查询维修预约列表失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 更新维修预约状态
     */
    @Log(title = "更新维修预约状态", businessType = BusinessType.UPDATE)
    @PostMapping("/status")
    public AjaxResult updateReservationStatus(@RequestParam Long reservationId, 
                                            @RequestParam String status) {
        try {
            int result = repairService.updateReservationStatus(reservationId, status);
            if (result > 0) {
                log.info("更新维修预约状态成功，预约ID：{}，状态：{}", reservationId, status);
                return AjaxResult.success("状态更新成功");
            } else {
                return AjaxResult.error("状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新维修预约状态失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取维修预约详情
     */
    @GetMapping("/{reservationId}")
    public AjaxResult getReservationDetail(@PathVariable Long reservationId) {
        try {
            RepairReservation reservation = repairService.getReservationById(reservationId);
            if (reservation != null) {
                log.info("获取维修预约详情成功，预约ID：{}", reservationId);
                return AjaxResult.success("查询成功", reservation);
            } else {
                return AjaxResult.error("预约记录不存在");
            }
        } catch (Exception e) {
            log.error("获取维修预约详情失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 取消维修预约
     */
    @Log(title = "取消维修预约", businessType = BusinessType.UPDATE)
    @PostMapping("/cancel/{reservationId}")
    public AjaxResult cancelReservation(@PathVariable Long reservationId) {
        try {
            int result = repairService.cancelReservation(reservationId);
            if (result > 0) {
                log.info("取消维修预约成功，预约ID：{}", reservationId);
                return AjaxResult.success("取消成功");
            } else {
                return AjaxResult.error("取消失败");
            }
        } catch (Exception e) {
            log.error("取消维修预约失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }
}
